package com.module.core.shiro;

import com.module.model.Permission;
import com.module.model.Role;
import com.module.model.UserInfo;
import com.module.service.PermissionService;
import com.module.service.RoleService;
import com.module.service.UserService;
import com.module.utils.MD5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;



/**
 * 用户身份验证,授权 Realm 组件
 *
 **/
public class SecurityRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionService permissionService;

    /**
     * 权限检查
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = String.valueOf(principals.getPrimaryPrincipal());

        final UserInfo user = userService.getUserByName(username);
        final Role role = roleService.getRoleById(user.getId());
        authorizationInfo.addRole(role.getTips());
        List<Permission>permissions= permissionService.selectById(role.getId());
        for (Permission permission : permissions) {
            // 添加权限
            authorizationInfo.addStringPermission(permission.getName());
        }
        return authorizationInfo;
    }

    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = String.valueOf(token.getPrincipal());
        String password = String.copyValueOf(((UsernamePasswordToken) token).getPassword());
        UserInfo info=userService.getUserByName(username);
        if(info==null){
            throw new UnknownAccountException("用户名不存在");
        }
        MD5Util util=new MD5Util(info.getSalt());

        if(!util.isPasswordValid(info.getUserPwd(),password)){
            throw new IncorrectCredentialsException("密码不正确");
        }
        ShiroUser shiroUser=new ShiroUser();
        shiroUser.id=info.getId();
        shiroUser.account=info.getUserName();
        shiroUser.name=info.getUserRealName();
        shiroUser.roleNames=roleService.getRoleById(info.getRoleid()).getTips();
        if (!shiroUser.roleNames.equals(RoleSign.ADMIN)){
            throw new AuthenticationException("用户无权限");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(shiroUser, password, getName());
        return authenticationInfo;
    }

}